package cnooc.dataAnalysis.service.impl;



import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cnooc.common.config.InfluxDbComUtil;
import cnooc.dataAnalysis.domain.AnalysisParam;
import cnooc.dataAnalysis.service.TransientService;
import cnooc.energy.domain.DeviceDataLocation;
import cnooc.energy.domain.Equipment;
import cnooc.energy.mapper.DeviceDataLocationMapper;
import cnooc.energy.mapper.EquipmentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询瞬时数据MService业务层处理
 *
 * @author 韩是非
 * @date 2023-11-28
 */
@Slf4j
@Service
public class TransientServiceImpl implements TransientService {
    @Resource
    InfluxDbComUtil influxDbComUtil;

    @Resource
    EquipmentMapper equipmentMapper;

    @Resource
    DeviceDataLocationMapper deviceDataLocationMapper;

    private static final String QUERY_INSTANTANEOUS_DATA = "SELECT mean({}) * {} AS num FROM {} WHERE time >= '{}' AND time < '{}' GROUP BY time(5m) fill(0)  tz('Asia/Shanghai')  ";

    @Override
    public Map<String, List> queryInstantaneousData(AnalysisParam param) {
        SimpleDateFormat sdf = DateUtil.newSimpleFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, List> resultMap = new HashMap<>();
        List<String> xData = CollUtil.newArrayList();
        List<String> yData = CollUtil.newArrayList();

        Equipment equipment = equipmentMapper.selectEquipmentById(param.getDeviceId());
        DeviceDataLocation deviceDataLocation = deviceDataLocationMapper.selectDeviceDataLocationById(param.getLocationId());

        String queryStr
                = StrUtil.format(QUERY_INSTANTANEOUS_DATA, deviceDataLocation.getLocation(),deviceDataLocation.getVariationRatioCoefficient()==null?"1":deviceDataLocation.getVariationRatioCoefficient(), equipment.getTableName(), sdf.format(DateUtil.beginOfDay(param.getDatetime())), sdf.format(DateUtil.endOfDay(param.getDatetime())));

        List<Map<String, Object>> results = influxDbComUtil.query(queryStr);
        for (Map result : results) {
            String time = result.get("time").toString();
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(time, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            String format = zonedDateTime.format(targetFormatter);
            xData.add(format);
            yData.add(result.get("num").toString());
        }
        resultMap.put("xData", xData);
        resultMap.put("yData", yData);
        return resultMap;
    }
}
